package wiBase.baseUtil;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public abstract class PausableScheduledTask {

	private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
	private volatile boolean isPaused = false;

	abstract void task();

	public void start() {
		if (executor == null || executor.isShutdown()) {
			executor = Executors.newSingleThreadScheduledExecutor();
		} else {
			resume();
		}

		final Runnable beeper = new Runnable() {
			@Override
			public void run() {
				if (!isPaused)
					task();
			}
		};
		executor.scheduleAtFixedRate(beeper, getInitialDelay(), getPeriodDelay(), TimeUnit.SECONDS);
	}

	public void pause() {
		isPaused = true;
	}

	public void resume() {
		isPaused = false;
	}

	public void stop() {
		executor.shutdownNow();
		executor = null;
	}

	public long getInitialDelay() {
		return 0;
	}

	public long getPeriodDelay() {
		return 0;
	}

	public TimeUnit getTimeUnit() {
		return TimeUnit.SECONDS;
	}
}